package net.pingfang.util;


import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数字工具类
 *
 * @Author: CM
 * @Date: 2022/6/30 16:50
 */
public class NumberUtil {
    private static final String IS_NUMERIC = "[0-9]*";
    private static final String IS_DOUBLE = "[0-9]+[.]{0,1}[0-9]*[dD]{0,1}";


    /**
     * 校验是否为数字
     *
     * @param str 入参
     * @return 校验结果
     */
    public static boolean isNumeric(String str) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile(IS_NUMERIC);
        return pattern.matcher(str).matches();
    }

    /**
     * 字符串转换为数字
     *
     * @param number 字符串
     * @return 数字
     */
    public static Integer stringToInteger(String number) {
        if (StringUtils.isEmpty(number) || !isNumeric(number)) {
            return null;
        }
        return Integer.valueOf(number);
    }

    /**
     * 字符串转换为数字
     *
     * @param number 字符串
     * @return 数字
     */
    public static Double stringToDouble(String number) {
        if (StringUtils.isEmpty(number) || !isDouble(number)) {
            return 0D;
        }
        return Double.valueOf(number);
    }

    /**
     * 数字转换为字符串
     *
     * @param number 字符串
     * @return 数字
     */
    public static String integerToString(Integer number) {
        return String.valueOf(number == null ? null : String.valueOf(number));
    }

    public static boolean isDouble(String str){
        Pattern pattern = Pattern.compile(IS_DOUBLE);
        Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }
}
